// lib/utils/loading.dart

import 'package:f_enjoy_plus/core/constants/app_colors.dart';
import 'package:flutter/material.dart';

class LoadingUtils {
  // 单例模式
  static final LoadingUtils _instance = LoadingUtils._internal();
  factory LoadingUtils() => _instance;
  LoadingUtils._internal();

  // 全局key，用于获取BuildContext
  static final GlobalKey<NavigatorState> navigatorKey = GlobalKey<NavigatorState>();
  
  // 是否正在显示loading
  static bool _isShowing = false;
  
  // Dialog context (用于关闭对话框)
  static BuildContext? _dialogContext;

  /// 显示全局loading
  static void show({String? message}) {
    if (_isShowing) return;
    
    final context = navigatorKey.currentContext;
    if (context == null) {
      print('无法获取有效的context，loading无法显示');
      return;
    }
    
    _isShowing = true;
    
    // 使用showDialog而不是Overlay
    showDialog(
      context: context,
      barrierDismissible: false, // 点击外部不关闭
      barrierColor: Colors.black.withOpacity(0.3),
      builder: (BuildContext dialogContext) {
        _dialogContext = dialogContext;
        return WillPopScope(
          onWillPop: () async => false, // 禁止返回键关闭
          child: Center(
            child: Container(
              padding: EdgeInsets.all(20),
              decoration: BoxDecoration(
                color: AppColors.white,
                borderRadius: BorderRadius.circular(8),
                boxShadow: [
                  BoxShadow(
                    color: Colors.black.withOpacity(0.1),
                    blurRadius: 10,
                    spreadRadius: 1,
                  ),
                ],
              ),
              child: Column(
                mainAxisSize: MainAxisSize.min,
                children: [
                  CircularProgressIndicator(
                    valueColor: AlwaysStoppedAnimation<Color>(AppColors.primary),
                  ),
                  if (message != null) ...[
                    SizedBox(height: 16),
                    Text(
                      message,
                      style: TextStyle(fontSize: 14, color: AppColors.textPrimary),
                    ),
                  ],
                ],
              ),
            ),
          ),
        );
      },
    );
  }

  /// 隐藏全局loading
  static void hide() {
    if (!_isShowing) return;
    
    try {
      if (_dialogContext != null) {
        Navigator.of(_dialogContext!).pop();
      }
    } catch (e) {
      print('关闭loading对话框时出错: $e');
    } finally {
      _dialogContext = null;
      _isShowing = false;
    }
  }
  
  // 简便方法：在异步操作期间显示loading
  static Future<T> wrap<T>({
    required Future<T> Function() asyncFunction,
    String? message,
  }) async {
    try {
      show(message: message);
      return await asyncFunction();
    } finally {
      hide();
    }
  }
}